//
//  main.cpp
//  TRKUTIL
//
//  Created by 李通洲 on 15/1/24.
//  Copyright (c) 2015年 Wicresoft. All rights reserved.
//

#include <cstdlib>
#include <cstring>
#include <ctime>
#include <string>
#include <algorithm>

#include "Helper.hpp"
#include "LogManager.hpp"
#include "ConfigManager.hpp"

int main(int argc, const char *argv []) {
    LogManager& logger = LogManager::getInstance();
    std::string command = LoadConfig();

    {
        std::string pCalled;
        for (int i = 0; i < argc; ++i) {
            pCalled += argv[i];
            pCalled += ' ';
        }
        logger.LogInfo("Received: " + pCalled);
    }

    if (argc < 3) {
        panic("Error number of parameters! 2 params or more expected!");
    }

    if (std::strcmp(argv[1], "SendEvent")) {
        logger.LogWarning(std::string("Unknown TRKUTIL parameter type found: ") + argv[1]);
    }

    std::string params = argv[2];  // "HeartBeat=1,A=2,B=3";
    for (int i = 3; i < argc; ++i) {
        params += ' ';
        params += argv[i];
    }
    std::replace(params.begin(), params.end(), ',', ';');
    std::replace(params.begin(), params.end(), '"', '\'');
    command += '"';
    command += params;
    command += '"';

    double clock = 0;
    if (logger.GlobalLogLevel <= Info) {
        logger.LogInfo("Executing: " + command);
        clock = get_wall_time();
    }

    if (std::system(command.c_str())) {
        logger.LogError("Error executing msend!");
    }

    if (logger.GlobalLogLevel <= Info) {
        clock = get_wall_time() - clock;
        logger.LogInfo(fmt::sprintf("Process executed in %f s", clock));
    }
}
